/*
 * Copyright  2003-2005 The Apache Software Foundation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package it.secse.google.wrapper;



import java.net.URL;
import java.util.Date;
import java.util.List;

import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Person;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.extensions.EventEntry;
import com.google.gdata.data.extensions.EventFeed;
import com.google.gdata.data.extensions.When;
import com.google.gdata.data.extensions.Where;


public class SimpleService {
	

	
    public String echo(String arg) throws java.lang.Exception {
       	System.out.println("Tomcat service accessed successfully.. :)");
        return Credential.getInstance().getPassword();
    }
    

	
	// username => nome del calendario (userAgeda nella richiesta soap) => quello che fa il binding
	// mailbox => indirizzo mail da usare per il login (Agenda nella richiesta soap)
	
	public void requestMeeting(java.lang.String mailbox, java.lang.String requestSubject, java.lang.String description, java.lang.String location,
			java.util.Calendar start, java.util.Calendar end) throws java.rmi.RemoteException {
		try {
			String email = Credential.getInstance().getEmail();
			String password = Credential.getInstance().getPassword();
			
			System.out.println("\n\n\n\n\nINIZIO\n\n\n\n\n\n\n ");
			System.out.println("\n\n\n\n\nMAILBOX " + mailbox);
			System.out.println("\n\n\n\n\nPASSWORD " + password);
			System.out.println("\n\n\n\n\nUSERNAME " + email);
			
			// da eliminare per baco non nostro sui paramentri entranti
			// mailbox="gianluca.ripa@gmail.com";
			// da eliminare con versione di EMIC con accesso condivisione in scrittura
			// password="ripagl74"; eliminata

			URL postUrl = new URL("http://www.google.com/calendar/feeds/" + mailbox + "/private/full");
			EventEntry myEntry = new EventEntry();

			myEntry.setTitle(new PlainTextConstruct(requestSubject));
			myEntry.setContent(new PlainTextConstruct(description));

			Person author = new Person(email);
			myEntry.getAuthors().add(author);

			Where eventLoc = new Where();
			eventLoc.setLabel(location);
			myEntry.addLocation(eventLoc);

			DateTime startTime = new DateTime(start.getTimeInMillis());
			DateTime endTime = new DateTime(end.getTimeInMillis());
			When eventTimes = new When();
			eventTimes.setStartTime(startTime);
			eventTimes.setEndTime(endTime);
			myEntry.addTime(eventTimes);

			CalendarService myService = new CalendarService(email);
			//myService.setUserCredentials("roberto24680@hotmail.com", "SeCSEDemo2006");
			myService.setUserCredentials(email, password);
			

			
			// Send the request and receive the response:
			EventEntry insertedEntry = myService.insert(postUrl, myEntry);

		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}
	}

	public boolean checkSchedule(java.lang.String strMailbox, java.util.Calendar start, java.util.Calendar end) throws java.rmi.RemoteException {

		
		boolean response = false;
		int size = 0;
		String[] stitle=null;
		String[] slocation=null;
		String[] sbusy=null;
		long[] sstart=null;
		long[] send=null;
		String email = Credential.getInstance().getEmail();
		String password = Credential.getInstance().getPassword();
		
		try {
		
			//CODICE EMIC
			
//			try {
//			PORTTYPEICredentialProviderAPIProxy proxy = new PORTTYPEICredentialProviderAPIProxy();
//			GetSecurityToken token = new GetSecurityToken();
//			token.setCallbackAddress("http://" + password + ":8015/clientcallback");
//			token.setServiceAddress("http://schemas.google.com/gCal/2005#editor");
//			token.setDelegatee(secseEmail);
//			token.setDelegator(strMailbox);
//			proxy.OPERATIONGetSecurityToken(token);
//			} catch(Exception e) {}
			
			Thread.sleep(500);
			

	    	//FINE CODICE EMIC
			URL feedUrl = new URL("http://www.google.com/calendar/feeds/" + strMailbox + "/private/basic");
			CalendarService myService = new CalendarService(email);
			//myService.setUserCredentials("roberto24680@hotmail.com", "SeCSEDemo2006");

			System.out.println("\n\nEMAIL   " + email);
			System.out.println("\n\nPASSWORD   " + password);

			
			myService.setUserCredentials(email, password);
			
			
			
			System.out.println("\n\n\n\n\nINIZIO\n\n\n\n\n\n\n ");
//			System.out.println("\n\n\n\n\nSTREXCHSRV " + strExchSvrName);
			System.out.println("\n\n\n\n\nMAILBOX " + strMailbox);
			System.out.println("\n\n\n\n\nPASSWORD " + password);
//			System.out.println("\n\n\n\n\nUSERNAME " + userName);
//			System.out.println("\n\n\n\n\nDOMAIN " + domain);
			System.out.println("\n\n\n\n\nSTART " + start.getTime().toString());
			System.out.println("\n\n\n\n\nEND " + end.getTime().toString());
			System.out.println("\n\n\n\n\nSTART " + start.toString());
			System.out.println("\n\n\n\n\nEND " + end.toString());			

			CalendarQuery myQuery = new CalendarQuery(feedUrl);
			myQuery.setMaxResults(100);
			
			Date date = start.getTime();
			date.setHours(date.getHours()-2);
			start.setTime(date);

			date = end.getTime();
			date.setHours(date.getHours()-2);
			end.setTime(date);
			
			DateTime gstart = new DateTime(start.getTimeInMillis());
			DateTime gend = new DateTime(end.getTimeInMillis());
			myQuery.setMinimumStartTime(gstart);
			myQuery.setMaximumStartTime(gend);

			// Send the request and receive the response:
			EventFeed resultFeed = myService.query(myQuery, EventFeed.class);

			System.out.println("\n\n\n\n\nINIZIO\n\n\n\n\n\n\n ");
			System.out.println("\n\n\n\n\nMAILBOX " + strMailbox);
			System.out.println("\n\n\n\n\nPASSWORD " + password);
			System.out.println("\n\n\n\n\nUSERNAME " + email);
			System.out.println("\n\n\n\n\nSTART " + start.getTime().toString());
			System.out.println("\n\n\n\n\nEND " + end.getTime().toString());

			
			// Print the title of the returned feed:
			System.out.println(resultFeed.getTitle().getPlainText());
			List entries = resultFeed.getEntries();
			System.out.println("sizein:" + entries.size());
			size = entries.size();
			if ( size >=1 ) response = true;
			stitle = new String[size];
			slocation = new String[size];
			sbusy = new String[size];
			sstart = new long[size];
			send = new long[size];

			for (int i = 0; i < entries.size(); i++) {
				EventEntry entry = (EventEntry) entries.get(i);
			
				// subject
				String title = entry.getTitle().getPlainText();
				System.out.println(title);
				stitle[i] = title;
			
				// location
//				List wheres = entry.getLocations();
//				Where where = (Where) wheres.get(0);
//				String location = where.getLabel();
//				System.out.println(location);
//				slocation[i] = location;
//			
//				// start
//				List whens = entry.getTimes();
//				When when = (When) whens.get(0);
//				DateTime d1 = when.getStartTime();
//				System.out.println("\n\n\n\n\n\n\n\n\n\n\nstart:" + d1.toString() + " long: " + d1.getValue());
//				long nstart = d1.getValue();
//				sstart[i] = nstart;
//		
//				// end
//				DateTime d2 = when.getEndTime();
//				System.out.println("\n\n\n\n\n\n\n\n\n\n\nend:" + d2.toString() + " long: " + d2.getValue());
//				long nend = d2.getValue();
//				send[i] = nend;
//		
//				// busystatus
//				String status = entry.getStatus().getValue();
//				int pos=status.indexOf("#");
//				status=status.substring(pos+1,status.length());
//				status=status.replaceFirst("event.","");
//				sbusy[i] = status;
//		
//				// instancetype

			}
			
		} catch (java.lang.Exception e) {
			e.printStackTrace();
			System.out.println("eccezione");
		}

		System.out.println("risposta");
//		Appointment[] Aapp = new Appointment[size];
//		for (int i = 0; i < size; i++) {
//
//			Appointment app = new Appointment();
//			app.setBusyStatus(sbusy[i]);
//			Calendar c1 = new GregorianCalendar();
//			c1.setTimeInMillis(sstart[i]);
//			app.setStartTime(c1);
//			Calendar c2 = new GregorianCalendar();
//			c2.setTimeInMillis(send[i]);
//			app.setEndTime(c2);
//			app.setInstanceType(0);
//			app.setLocation(slocation[i]);
//			app.setSubject(stitle[i]);
//			Aapp[i] = app;
//		}
//		response.setAppointment(Aapp);
		return response;		

}


	

	
	
	
}
